<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 存款
 */
declare (strict_types=1);

namespace app\api\controller;

use app\api\base\controller\Base;
use app\api\validate\RechargeValidate;
use app\extend\model\User;

class Recharge extends Base
{
    /**
     * 列表
     */
    public function getList()
    {
        $validate = new RechargeValidate();
        $ret = $validate->scene('getList')->check(input());
        if(!$ret){
            return json(_E($validate->getError()));
        }

        $page = input('page/d',1);
        $limit = input('limit/d',20);

        $where = [
            ['uid','=',self::$UserInfo['id']]
        ];

        $list = [];
        $count = \app\extend\model\Recharge::where($where)->count();
        if($count > 0){
            $list = \app\extend\model\Recharge::where($where)->order(['id' => 'desc'])->page($page)->limit($limit)->select();
        }

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'count' => $count,
            'data' => $list,
        ])->send();
    }

    /**
     * 充值
     */
    public function recharge()
    {
        if (request()->isPost()) {
            $validate = new RechargeValidate();
            $ret = $validate->scene('recharge')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $money = input('money', 0);

            $userInfo = User::where([
                ['id','=',self::$UserInfo['id']]
            ])->field('id,balance,status')->find();

            if($userInfo['status'] != 0){
                return json(_E('抱歉！您暂时无权充值'));
            }

            //获取网站配置
            $websiteConfigInfo = \app\extend\model\WebsiteConfig::where([
                ['id','=',1]
            ])->find();

            //判断充值金额区间
            if($money < $websiteConfigInfo['recharge_min_money'] || $money > $websiteConfigInfo['recharge_max_money']){
                return json(_E('单笔入金金额在'.$websiteConfigInfo['recharge_min_money'].'-'.$websiteConfigInfo['recharge_max_money'].'之间'));
            }

            $result = \app\extend\model\Recharge::insert([
                'uid' => self::$UserInfo['id'],
                'money' => $money,
                'balance' => $userInfo->balance,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if(!$result){
                return json(_E('提交失败'));
            } else {
                return json(_S('提交成功，请联系客服到账，谢谢！'));
            }
        }
    }
}
